package top.hkyzf.study.leetcode.tree;

import org.junit.Test;

/**
 * description: 
 * @author zhufeng
 * @date 2024/2/26 0026 9:33
 * @version V1.0
 */
public class 二叉搜索树的范围和_938 {
    private int sum = 0;
    public int rangeSumBST(TreeNode root, int low, int high) {
        dfs(root, low, high);
        return sum;
    }

    public void dfs(TreeNode node, int low, int high) {
        if (node == null) {
            return;
        }
        if (node.val >= low && node.val <= high) {
            sum += node.val;
        }
        dfs(node.left, low, high);
        dfs(node.right, low, high);
    }

    @Test
    public void testRangeSumBST () {
        TreeNode l2 = new TreeNode(3);
        TreeNode r2 = new TreeNode(7);
        TreeNode r3 = new TreeNode(18);
        TreeNode l1 = new TreeNode(5, l2, r2);
        TreeNode r1 = new TreeNode(15, null, r3);
        TreeNode root = new TreeNode(10, l1, r1);
        int low = 7;
        int high = 15;
        System.out.println(rangeSumBST(root, low, high));
    }
}
